<!-- CheckboxGroup.svelte -->
<script lang="ts">
	import { setContext } from 'svelte';
	import { CHECKBOX_GROUP_CONTEXT_KEY } from './context';
	import type { CheckboxGroupContext, CheckboxRegistry, Variant } from './types';

	// 1. 定义回调函数 prop（替代事件派发）
	export let onchange: ((values: any[]) => void) | undefined = () => {};

	// 组件原有属性
	export let modelValue: any[] = [];
	export let disabled: boolean = false;
	export let name: string = '';
	export let size: 'sm' | 'md' | 'lg' = 'md';
	export let variant: Variant = 'primary';
	export let className: string = '';
	export let buttonStyle: boolean = false;
	export let fill: string = '';
	export let textColor: string = '';

	const checkboxes = new Set<CheckboxRegistry>();

	// 2. 组上下文（移除事件相关逻辑，改用回调）
	const groupContext: CheckboxGroupContext = {
		disabled,
		name,
		size,
		variant,
		buttonStyle,
		fill,
		textColor,
		register: (checkbox: CheckboxRegistry) => {
			checkboxes.add(checkbox);
			checkbox.updateChecked(modelValue.includes(checkbox.value));
			return () => checkboxes.delete(checkbox);
		},
		onToggle: (value: any) => {
			// 计算新的选中值
			const isChecked = modelValue.includes(value);
			modelValue = isChecked ? modelValue.filter((item) => item !== value) : [...modelValue, value];

			// 同步子复选框状态
			checkboxes.forEach((checkbox) => {
				checkbox.updateChecked(modelValue.includes(checkbox.value));
			});

			// 3. 调用回调函数通知外部（替代 dispatch）
			onchange?.(modelValue);
		}
	};

	setContext(CHECKBOX_GROUP_CONTEXT_KEY, groupContext);

	// 监听 modelValue 变化，同步子组件状态
	$: {
		checkboxes.forEach((checkbox) => {
			checkbox.updateChecked(modelValue.includes(checkbox.value));
		});
	}

	// 监听组属性变化，更新上下文
	$: groupContext.disabled = disabled;
	$: groupContext.size = size;
	$: groupContext.variant = variant;
	$: groupContext.buttonStyle = buttonStyle;
	$: groupContext.fill = fill;
	$: groupContext.textColor = textColor;

	$: {
		// 增加空数组校验，避免 undefined 导致的异常
		const safeModelValue = Array.isArray(modelValue) ? modelValue : [];
		checkboxes.forEach((checkbox) => {
			checkbox.updateChecked(safeModelValue.includes(checkbox.value));
		});
	}
</script>

<div class={`checkbox-group ${buttonStyle ? 'checkbox-group--button' : ''} ${className}`}>
	<slot />
</div>

<style lang="scss" scoped>
	.checkbox-group {
		display: inline-flex;
		flex-direction: row;
		gap: 8px;
		&.checkbox-group--button {
			gap: 0;
		}
	}
</style>
